package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private String serverIp;
    private int serverPort;
    private DatagramSocket socket;
    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        //客户端不用程序员手动指定端口，系统自动分配即可
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动！");
        while(true) {
            //1.从控制端读入数据并构造请求
            Scanner scanner = new Scanner(System.in);
            System.out.print("-> ");
            String request = scanner.nextLine();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            socket.send(requestPacket);
            //2.解析响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //3.打印
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9650);
        client.start();
    }
}
